package com.langsin.my0628;

/*
* 张睿智
* */

import com.langsin.bean.User;
import com.langsin.zhangruizhi.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;

public class ZRZTest {
    @Test
    public void testCache1() throws Exception{
        /*一级缓存*/
//mybatis一级缓存是存在sqlSession的内存map里的
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession = sessionFactory.openSession();;
        //查询第一次
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.queryById(702);
        System.out.println(user);

        Thread.sleep(2000);

        //同一个sqlSession查询第二次
        User user2 = userMapper.queryById(702);
        System.out.println(user2);

        //如果同一个会话对象进行了增删改，缓存就会失效@Test
    }

//    二级缓存需要我们的对象能够序列化 二级缓存 有可能是存入到硬盘中的
    @Test
    public void testCache2() throws Exception{
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession1 = sessionFactory.openSession();;
//第一个会话的查询
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = mapper1.queryById(702);
        System.out.println(user1);
        sqlSession1.close();

        Thread.sleep(2000);
        System.out.println("休眠2s时间到");

//第二个会话
        SqlSession sqlSession2 = sessionFactory.openSession();
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = mapper2.queryById(702);
        System.out.println(user2);
        sqlSession2.close();
        /*
        * 休眠2s时间到
 WARN [main] - As you are using functionality that deserializes object streams, it is recommended to define the JEP-290 serial filter. Please refer to https://docs.oracle.com/pls/topic/lookup?ctx=javase15&id=GUID-8296D8E8-2B93-4B9A-856E-0A65AF9B8C66
DEBUG [main] - Cache Hit Ratio [com.langsin.zhangruizhi.mapper.UserMapper]: 0.5
User(userId=702, userName=lisisi, roleCode=plain, userPass=123, cname=小思, isLogin=0, telphone=13887654321, address=山师长清分校, nation=中国, email=lisisi@163.com, userImg=null, gender=1, ordersList=null)
       因为其运行结果没有走预编译，然后查询，因此是从缓存区进行调出的
        * */
    }
}
